<template>

  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card style="margin: 20px auto;">
      <!-- 提示区域：alert组件，:closable="false"移除原有的关闭叉叉按钮 -->
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>
      <!-- 步骤条区域：用到了Element-plus的Steps进度条组件 -->
      <!-- 这里activeIndex-0是因为后面Tab绑定了activeIndex对象，输入的是字符串，减0后会将其强制转换为数字类型。 -->
      <el-steps :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品种类"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
    </el-card>
    <!-- Tab栏区域 -->
    <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" label-position="left">
      <el-tabs :tab-position="'left'" v-model="activeIndex">
        <el-tab-pane label="基本信息" name="1">
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="addForm.name"></el-input>
          </el-form-item>
          <el-form-item label="副标题" prop="subTitle">
            <el-input v-model="addForm.subTitle" type="textarea"></el-input>
          </el-form-item>
          <div class="input-box">
            <el-form-item label="商品价格" prop="price">
              <el-input v-model.number="addForm.price" type="number" placeholder="请输入商品价格" />
            </el-form-item>
            <el-form-item label="商品数量" prop="stock">
              <el-input v-model.number="addForm.stock" type="number"></el-input>
            </el-form-item>
            <el-form-item label="是否上架">
              <el-switch v-model="addForm.status" />
            </el-form-item>
            <el-form-item label="是否热门">
              <el-switch v-model="addForm.hotFlag" />
            </el-form-item>
          </div>

          <el-form-item label="分类名称" class="category">
            <el-select v-model="addForm.categoryId" placeholder="请选择一级分类">
              <el-option v-for="item in categories" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
            <el-select v-model="addForm.subCategoryId" placeholder="请选择二级分类">
              <el-option v-for="item in subCategories" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>

        </el-tab-pane>


        <el-tab-pane label="商品种类" name="2">
          <ProductParam @update_param="handleUpdatparam" :data="addForm.param" />
        </el-tab-pane>
        <el-tab-pane label="商品图片" name="3">
          <ProductImage @mainImage="handleUpdateMainImage" @subImages="handleUpdateSubImages"/>
        </el-tab-pane>
        <el-tab-pane label="商品详情" name="4">
          <ProductDetail @vHtml="handlevHtml" />
        </el-tab-pane>
        <el-tab-pane label="提交内容" name="5">
          <ProductPreview :form="addForm" />
        </el-tab-pane>

      </el-tabs>
    </el-form>

    <div class="btn-group" v-if="activeIndex == 5">
      <el-button type="primary" @click="commitForm">提交内容</el-button>
      <el-button @click="resetForm">重置表单</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { getCategories, getSubCategories,addProduct } from '@/apis/product.js';
import ProductParam from './ProductParam.vue';
import ProductImage from './ProductImage.vue';
import ProductDetail from './ProductDetail.vue';
import ProductPreview from './ProductPreview.vue';
import {ElMessage} from "element-plus";

const activeIndex = ref(0);
const addForm = reactive({
  name: '',
  price: null,
  subTitle: '',
  stock: null,
  categoryId: null,
  categoryName:'',
  subCategoryId: null,
  subCategoryName:'',
  mainImage :'',
  subImages:[],
  param: [
  ],
  detail: '',
  hotFlag: false,
  status: true,
});
const addFormRef = ref(null);

const categories = ref([]);
const subCategories = ref([]);

// 处理商品参数更新
const handleUpdatparam = (param) => {
  addForm.param = param;
};

const handleUpdateMainImage = (val) => {
  console.log(val);
  addForm.mainImage = val;
};

const handleUpdateSubImages = (val) => {
  console.log(val);
  addForm.subImages = val;
};

// 处理商品详情更新
const handlevHtml = (val) => {
  console.log(val);
  addForm.detail = val
}

const addFormRules = ref({
  name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' },
    { type: 'number', message: '商品价格必须为数字', trigger: 'blur' },
  ],
  stock: [
    { required: true, message: '请输入商品数量', trigger: 'blur' },
    { type: 'number', message: '商品数量必须为数字', trigger: 'blur' },
  ],
});


const setSubCategories = async (categoryId) => {
  const res = await getSubCategories(categoryId);
  subCategories.value = res;
  console.log(res);
};

// 提交表单
const commitForm = () => {
  addFormRef.value.validate((valid, fields) => {
    if (valid) {
      addProduct(addForm)
          .then(() => {
            resetForm();
            ElMessage.success('添加成功');
          })
          .catch((err) => {
            console.error(err);
            ElMessage.error('添加失败，请稍后再试');
          });
    } else {
      const firstErrorField = Object.keys(fields)[0];
      const firstErrorMessage = fields[firstErrorField][0].message;
      ElMessage.error(`错误提示: ${firstErrorMessage}`);
    }
  });
};
  const resetForm = () => {
    // 逐个属性重置
    addFormRef.value.resetFields();
    activeIndex.value = 0;
  }

onMounted(async () => {
  const res = await getCategories();
  categories.value = res;

  // 监听一级分类的变化
  watch(
    () => addForm.categoryId,
    (newValue, oldValue) => {
      // console.log(newValue, oldValue);
      if (newValue !== oldValue && newValue !== null) {
        // 根据一级分类的值，获取对应的二级分类列表
        setSubCategories(newValue);
      }
    },
    { immediate: true }
  );

     watch(addForm, addForm.subCategoryId
     , (newVal) => {
      addForm.categoryName = categories[categoryId];
      addForm.subCategoryName = subCategories[newVal];
    }, { deep: true, immediate: true });

});

</script>

<style scoped lang="scss">
.el-steps {
  margin: 15px 0;
}

.el-step__title {
  font-size: 13px;
}

.category .el-select {
  width: 50%;
}

.input-box {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: center;
}
</style>
